package cn.itcast.bos.web.action;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemoUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope(value = "prototype")
public class CustomerAction extends BaseAction<Customer> {

	private static final long serialVersionUID = 1L;

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Action(value = "customer_sendSms", results = { @Result(type = "json") })
	public String sendSms() throws Exception {
		// 获取页面输入的电话号
		final String telephone = model.getTelephone();
		// 生成四位的验证码
		final String randomCode = SmsDemoUtils.getNumber();
		// 将手机号和验证码放到session中一份
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		// 以秒为单位，即在没有活动1分钟后，session将失效
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(1 * 60);
		System.out.println("生成手机验证码为：" + randomCode);

		// 使用短信平台系统（bos_Sms）发送短信，使用activerMQ,此时bos_fore是生产者
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", telephone);
				mapMessage.setString("code", randomCode);
				return mapMessage;
			}
		});
		// **************************可以省略（验证码回显）*****************************
		SendSmsResponse sendSmsResponse = SmsDemoUtils.sendSms(telephone, randomCode);
		// 表示发送成功
		if (sendSmsResponse.getCode().equals("OK")) {
			System.out.println("短信发送成功！手机号是：" + telephone + "，验证码是：" + randomCode);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("success", randomCode);

			// 优化回显手机号和验证码//不太清楚此处前段代码
			map.put("telephone", telephone);
			map.put("code", randomCode);

			ServletActionContext.getContext().getValueStack().push(map);
		} else {
			throw new RuntimeException("发送短信失败，请联系管理员");
		}
		// **************************可以省略（验证码回显）*****************************
		return SUCCESS;
	}

	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = { @Result(type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 先校验短信验证码，如果不通过，调回注册页面
		// 从session获取 之前生成验证码
		String checkcodeSession = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		if (checkcodeSession == null || !checkcodeSession.endsWith(checkcode)) {
			System.out.println("短信验证码错误...");
			return "input";
		} else {
			WebClient.create("http://localhost:9002/crm_management/services/customerService/customer")
					.type(MediaType.APPLICATION_JSON).post(model);
			System.out.println("客户注册成功！");

			// 发送绑定邮件，将激活码保存redis中
			// 发送一封激活邮件
			// 生成激活码（32为的随机生成数字，建议不要生成特殊字符）
			String activecode = RandomStringUtils.randomNumeric(32);

			// 将激活码保存redis中
			redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);

			String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
					+ model.getTelephone() + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
			// 邮件标题、内容、收件邮箱，激活码:已经放到邮件内容中 此处传递空 就可以了
			MailUtils.sendMail("测试邮件", content, model.getEmail(), "");

			return SUCCESS;
		}

	}

	// 属性驱动，邮件上传递的激活码
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail") // ,results={@Result(type="redrive",location="")}
	public String activeMail() throws Exception {
		// 在浏览器上显示错误 处理中文乱码
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 判断激活码是否有效
		String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activecodeRedis == null || !activecode.equals(activecodeRedis)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 激活码有效
			// 判断是否重复绑定，即T_CUSTOMER的TYPE字段是否为1
			// 调用CRM webService 查询客户信息，判断是否已经绑定
			Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL)
					.path("/services/customerService/customer/telephone/" + model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).get(Customer.class);// 指定查询哪个对象
			if (customer != null && customer.getType() != 1) {
				// 如果没被绑定
				// 没有绑定,进行绑定，更新type字段为1
				WebClient.create(Constants.CRM_MANAGEMENT_URL)
						.path("/services/customerService/customer/updatetype/" + model.getTelephone())
						.type(MediaType.APPLICATION_JSON).put(null);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过，无需重复绑定！");
			}
			// 删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}

		return NONE;
	}

	// 用户登陆
	@Action(value = "customer_login", results = { @Result(name = "login", type = "redirect", location = "login.html"),
			@Result(name = "success", location = "index.html#/myhome", type = "redirect") })
	public String login() {
		Customer customer = WebClient
				.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/customer/login?telephone="
						+ model.getTelephone() + "&password=" + model.getPassword())
				.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer == null) {
			System.out.println("当前电话号：" + model.getTelephone() + "登录或者密码错误！！");
			return LOGIN;
		} else {
			if (customer.getType() != 1) {
				System.out.println("当前电话号：" + model.getTelephone() + "，邮箱：" + model.getEmail() + "没有激活！！");
				return LOGIN;
			}
		}
		// 当前用户信息存放到Session中
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		return SUCCESS;
	}

}
